package com.common.library.util;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;


public class HttpClientUtils {
	
	public static final int CONNECT_TIMEOUT = 6000;
	public static final int SOCKET_TIMEOUT = 30000;
	
	
	/**
	 * 
	 * function: getFileSize
	 *
	 * @param url
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * 
	 * @ author: aXiBa 2011-11-22 下午02:17:19
	 */
	public static long getFileSize(String url) throws ClientProtocolException, IOException  {
		
		long result = 0L;
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpParams httpParams = httpclient.getParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, CONNECT_TIMEOUT);
		HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT);
		
		HttpGet httpGet = new HttpGet(url);
		
		HttpResponse response = httpclient.execute(httpGet);
		
		if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
			
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = entity.getContentLength();
			}
		}
		
		// 关闭连接
		httpGet.abort();
		httpclient.getConnectionManager().shutdown(); 
		
		return result;
	}	
	


	/**
	 * 
	 * function: 下载图片
	 *
	 * @param path
	 * @param outPath
	 * @param filename
	 * @return  返回：文件是否存在 
	 * 
	 * @ author: aXiBa 2013-6-4 上午11:09:06
	 */
	public static boolean downloadImage(String path, String outPath, String filename) {
	
		boolean isFileExist = true;
		HttpGet httpGet = null;
		DefaultHttpClient httpclient = null;

		try {
			httpclient = new DefaultHttpClient();
			HttpParams httpParams = httpclient.getParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, CONNECT_TIMEOUT);
		    HttpConnectionParams.setSoTimeout(httpParams, SOCKET_TIMEOUT);
	
		    httpGet = new HttpGet(path);
	
	        HttpResponse response = httpclient.execute(httpGet);
		
	        if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {	
	        	HttpEntity entity = response.getEntity();
	        	
	        	// 保存到sdcard中
	        	//43的判断为:为了防止错误域名请求返回的空白页面.
	        	//空白页面会返回一个长度为43的空白图片
	        	if (entity != null && entity.getContentLength() > 43) {
					FileUtils.writeContent2File(entity.getContent(), outPath, filename);
		        }
			}
	        // 文件不存在 
	        else {
	        	isFileExist = false;
	        }
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			
			// 关闭连接
			if(null!=httpGet) {
				httpGet.abort();
			}
			if(null!=httpclient) {
				httpclient.getConnectionManager().shutdown(); 
			}
		}
			
        return isFileExist;
	}
	
}
